package com.youth.framework.util;

import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

public class PageUtil {
	private static Pattern pattern = Pattern.compile("^\\d+$");
	private int pageIndex = -1;
	private int pageSize = -1;

	public PageUtil(HttpServletRequest request) {
		if (request != null) {
			String params = request.getParameter("page");
			if (params != null && pattern.matcher(params).find()) {
				this.pageIndex = Integer.parseInt(params);
			}

			params = request.getParameter("rows");
			if (params != null && pattern.matcher(params).find()) {
				this.pageSize = Integer.parseInt(params);
			}
		}
	}

	/**
	 * 返回一个值表示当前请求是否启用分页参数
	 * 
	 * @return
	 */
	public boolean isInvoked() {
		return this.pageIndex > 0 && this.pageSize > 0;
	}

	/**
	 * 获取从1开始的页的页码索引
	 * 
	 * @return the pageIndex
	 */
	public int getPageIndex() {
		return pageIndex;
	}

	/**
	 * 获取每页可显示的记录的最大条数
	 * 
	 * @return the pageSize
	 */
	public int getPageSize() {
		return pageSize;
	}
	
	/**
	 * 返回当前页表示的数据相对总记录的偏移量
	 * @return
	 */
	public int offset() {
		if (this.isInvoked()) {
			return (this.pageIndex - 1) * this.pageSize;
		}
		return 0;
	}
	
	/**
	 * 返回当前页要显示的数据最大条数
	 * @return
	 */
	public int limit() {
		return this.pageSize;
	}
}
